import { useMemo, useState } from 'react';

type Item = { name: string; spec: string; dose: string; freq: string; days: number };

export default function ProviderPrescribe() {
  const [patient, setPatient] = useState('张三');
  const [diag, setDiag] = useState('上呼吸道感染');
  const [items, setItems] = useState<Item[]>([
    { name: '对乙酰氨基酚片', spec: '0.5g*12片', dose: '0.5g', freq: 'q6h prn', days: 2 },
  ]);

  const json = useMemo(() => JSON.stringify({ patient, diag, items }, null, 2), [patient, diag, items]);

  function update(idx: number, key: keyof Item, v: string) {
    setItems(prev => prev.map((it, i) => i === idx ? { ...it, [key]: key === 'days' ? Number(v) : v } as any : it));
  }

  return (
    <div className="grid grid-cols-2 gap-3 px-4 pb-20">
      <div className="rounded-2xl bg-white p-4 shadow-sm space-y-3">
        <div className="grid grid-cols-2 gap-2 text-sm">
          <input value={patient} onChange={e => setPatient(e.target.value)} className="rounded-xl border px-3 py-2" placeholder="患者姓名" />
          <input value={diag} onChange={e => setDiag(e.target.value)} className="rounded-xl border px-3 py-2" placeholder="诊断" />
        </div>
        <div className="text-sm text-gray-600">处方明细</div>
        <div className="space-y-2">
          {items.map((it, i) => (
            <div key={i} className="grid grid-cols-5 gap-2 text-sm">
              <input value={it.name} onChange={e => update(i, 'name', e.target.value)} className="rounded-xl border px-3 py-2" placeholder="药品名称" />
              <input value={it.spec} onChange={e => update(i, 'spec', e.target.value)} className="rounded-xl border px-3 py-2" placeholder="规格" />
              <input value={it.dose} onChange={e => update(i, 'dose', e.target.value)} className="rounded-xl border px-3 py-2" placeholder="单次剂量" />
              <input value={it.freq} onChange={e => update(i, 'freq', e.target.value)} className="rounded-xl border px-3 py-2" placeholder="频次" />
              <input type="number" value={it.days} onChange={e => update(i, 'days', e.target.value)} className="rounded-xl border px-3 py-2" placeholder="天数" />
            </div>
          ))}
          <button className="text-brand-600 text-sm" onClick={() => setItems(arr => [...arr, { name: '', spec: '', dose: '', freq: '', days: 1 }])}>+ 添加药品</button>
        </div>
        <div className="flex gap-2 text-sm">
          <button className="rounded-xl bg-brand-600 px-4 py-2 text-white">生成处方</button>
          <button className="rounded-xl border px-4 py-2">清空</button>
        </div>
      </div>
      <div className="rounded-2xl bg-white p-4 shadow-sm">
        <div className="font-medium mb-2">预览 / 导出</div>
        <pre className="rounded-xl bg-gray-50 p-3 text-xs overflow-auto">{json}</pre>
      </div>
    </div>
  );
}


